<template>
    <div class="ant_layout">
        <!-- 左侧边栏 -->
        <div class="layout_sider">
            <!-- 区划树 -->
            <DataTree :treeData="apiTreeData" @changeRegionCode="changeRegionCodeFn" />
        </div>

        <!-- 主体 -->
        <div class="layout_content">
            <!-- 顶部按钮 -->
            <div class="content_opertors">
                <div class="left">
                    <a-button type="primary" @click="mainQuery">查询</a-button>
                    <a-button type="primary" @click="generateReport">重新生成报告</a-button>
                    <a-button type="primary" @click="exportExcel(dataSource, columns, '发生数预警（日）.xlsx')">导出</a-button>
                </div>
                <div class="right">
                    <a-form :model="topForm" name="basic" layout="inline" autocomplete="off">
                        <a-form-item label="金额单位：" name="amt_unit" :rules="[{ required: true }]">
                            <a-select v-model:value="topForm.amt_unit" style="width: 80px" @change="amtChangeFn">
                                <a-select-option :value="1">元</a-select-option>
                                <a-select-option :value="10000">万元</a-select-option>
                                <a-select-option :value="100000000">亿元</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-form>
                    <a-switch v-model:checked="tableOrEcharts" checked-children="图" un-checked-children="表" />
                </div>
            </div>
            <!-- 日期状态 -->
            <DatePanel :warningDate="warningDate" @changeDate="changeDate"></DatePanel>
            <!-- 表格区域 -->
            <!-- 以下注释是添加复选框和分页，功能已经实现 -->
            <!-- :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" :pagination="pagination" -->
            <div class="grid" :class="{'showOrhide': tableOrEcharts}">
                <a-table
                    :columns="columns"
                    :data-source="dataSource"
                    :rowKey="(record) => record.itemIndex"
                    bordered
                    size="small"
                    :scroll="{ y: '55vh' }"
                    :pagination="false"
                    :loading="loading"
                    @resizeColumn="handleResizeColumn"
                >
                    <template #bodyCell="{ text, record, index, column }">
                        <template v-if="column.key === 'progress'">
                            <a-popover v-if="!!text">
                                <template #content>
                                    <p>发生数：{{ record.realAmt }}</p>
                                    <p>预测数：{{ record.planAmt }}</p>
                                </template>
                                <a-progress :percent="text * 100" size="small" :format="(percent) => `${(text * 100).toFixed(2)}% (${record.realAmt}/${record.planAmt})`" />
                            </a-popover>
                        </template>
                        <template v-if="column.dataIndex === 'corrAmt'">
                            <div class="editable-cell">
                                <div v-if="editableData[index]" class="editable-cell-input-wrapper">
                                    <a-input style="width: 70%; margin-right: 10px" v-model:value="editableData[index].corrAmt" @pressEnter="save(index)" />
                                    <check-outlined class="editable-cell-icon-check" @click="save(index)" />
                                </div>
                                <div v-else class="editable-cell-text-wrapper">
                                    <span style="width: 70%; margin-right: 10px">{{ toThousands(text) || ' ' }}</span>
                                    <edit-outlined class="editable-cell-icon" @click="edit(index)" />
                                </div>
                            </div>
                        </template>
                    </template>
                </a-table>
            </div>
            <div class="my_echarts" :class="{'showOrhide': !tableOrEcharts}">
                <MyEcharts :echartsData="echartsData"></MyEcharts>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import DataTree from './Component/DataTree.vue';
import DatePanel from '@/components/CustomCalendar/DatePanel.vue';
import MyEcharts from '@/views/TreasuryWarningPhoto/Component/MyEcharts.vue';
import { message } from 'ant-design-vue';
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';
import { toTreeData, toThousands, exportExcel } from '@/util/common';
import { findColmunRepeatValIndexArr, checkIsHave } from '@/util/tableUtils';

import { regionTreeQuery } from '@/request/api/commonAPI';
import { reportQuery, generateQuery, modifyCorrAmt, warningDateQuery } from '@/request/api/treasuryWarningPhoto';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';

// 右上角年度月份、金额单位表单数据
let topForm = reactive({
    yearAndmonth: dayjs(),
    amt_unit: 10000,
});

// 金额选择框事件
const amtChangeFn = (date, option) => {
    mainQuery();
};

let warning_Level = ref<any>(null);

let templateQuotas:Array<any> = [];

let markLineData:Array<any> = [];

const warningInfo:any = (warningLevel:any) => {
    if (warningLevel == 1) {
        return { warningName: '工资支出预警', warningColor: 'red' };
    }
    if (warningLevel == 2) {
        return { warningName: '三保支出预警', warningColor: 'orange' };
    }
    if (warningLevel == 3) {
        return { warningName: '还本付息支出预警', warningColor: 'yellow' };
    }
    if (warningLevel == 4) {
        return { warningName: '定向支出预警', warningColor: 'green' };
    }
};

const getMarkLineData = (templateQuotas) => {
    markLineData.length = 0;
    if (templateQuotas.length && templateQuotas.length > 0) {
        templateQuotas.forEach((item, index) => {
            markLineData.push({
                name: warningInfo(item.warn_level).warningName,
                yAxis: item.warn_amt,
                lineStyle: { color: warningInfo(item.warn_level).warningColor, type: 'solid' },
            });
        });
    }
};

// 左侧区划树选中的区划code
const regionCode = ref([]);

const changeRegionCodeFn = (data: string[]) => {
    regionCode.value = data as any;
    setWarningDate()
    mainQuery();
};

// 选中日期
const selectedDate = reactive({
    'year':dayjs().get('year').toString(),
    'month':(dayjs().get('month')+1).toString().padStart(2, '0'),
    'day':dayjs().get('date').toString().padStart(2, '0')
})
const changeDate = (date:{'year':string,'month':string,'day':string}) => {
    selectedDate.year = date.year
    selectedDate.month = date.month
    selectedDate.day = date.day
}
watch(()=>selectedDate.day,(newValue,oldValue)=>{
  mainQuery()
})

// 设置预警日期
let warningDate = ref({})
const setWarningDate = () => {
    let params = {
        'mofDivCode':regionCode['value'][0]
    }
    if(params.mofDivCode !== undefined) {
        warningDateQuery(params).then((res:any) => {
            if(res.state == '200') {
                warningDate.value = res.data
                message.success(res.msg || '预警日期查询成功！');
            }else {
                message.error(res.msg || '预警日期查询失败！');
            }
        })
    }
}

/**
 * 表格相关
 */
// 分页
const pageSizeChange = (val, pageNum) => {
    pagination.pageSize = pageNum;
    pagination.current = 1;
    // const params = {
    //     rows: pagination.pageSize,
    //     page: pagination.current,
    // };
};
const pageChange = (page, val) => {
    pagination.current = page;
    // const params = {
    //     rows: pagination.pageSize,
    //     page: pagination.current,
    // };
    // queryFun();
};
const pagination = reactive({
    current: 1,
    pageSize: 50,
    showSizeChanger: true,
    total: 0,
    pageSizeOptions: ['50', '100', '200', '500'],
    showTotal: (total) => `共 ${total} 条数据`,
    onShowSizeChange: pageSizeChange,
    onChange: pageChange,
});
// dataSource
let dataSource = ref([]);
// 表头
const columns = ref([
    {
        title: '序号',
        dataIndex: 'itemIndex',
        key: 'itemIndex',
        width: 60,
        align: 'center',
        resizable: true,
        // customRender: ({text, record, index}) => index + 1,
        // customRender: ({ text, record, index }) => `${(pagination.current - 1) * pagination.pageSize + (index + 1)}`,
    },
    {
        title: '分类',
        dataIndex: 'itemGroup',
        key: 'itemGroup',
        width: 200,
        align: 'center',
        resizable: true,
        customCell: (_, index) => {
            console.log(typeof index);
            let repeatItemArr = findColmunRepeatValIndexArr(dataSource.value, 'itemGroup');
            let curColumnRepeatArr = checkIsHave(index, repeatItemArr);
            if (curColumnRepeatArr && curColumnRepeatArr.indexOf(index) === 0) {
                return { rowSpan: curColumnRepeatArr.length };
            }
            if (curColumnRepeatArr && curColumnRepeatArr.indexOf(index) > 0) {
                return { rowSpan: 0 };
            }
        },
    },
    {
        title: '项目',
        dataIndex: 'itemName',
        key: 'itemName',
        width: 300,
        align: 'left',
        resizable: true,
    },
    {
        title: '预测数',
        dataIndex: 'planAmt',
        key: 'planAmt',
        width: 200,
        align: 'right',
        resizable: true,
        customRender:({text}) =>{
            return toThousands(text)
        }
    },
    {
        title: '发生数',
        dataIndex: 'realAmt',
        key: 'realAmt',
        width: 200,
        align: 'right',
        resizable: true,
        customRender:({text}) =>{
            return toThousands(text)
        }
    },
    {
        title: '报告数',
        dataIndex: 'reportAmt',
        key: 'reportAmt',
        width: 200,
        align: 'right',
        resizable: true,
        customRender:({text}) =>{
            return toThousands(text)
        }
    },
    {
        title: '确认数',
        dataIndex: 'corrAmt',
        key: 'corrAmt',
        width: 200,
        align: 'right',
        resizable: true,
        customRender:({text}) =>{
            return toThousands(text)
        }
    },
    {
        title: '进度',
        dataIndex: 'progress',
        key: 'progress',
        width: 160,
        resizable: true,
        align: 'right',
    },
]);
const handleResizeColumn = (w, col) => {
    col.width = w;
};
// 加载动画
let loading = ref(false);
// 复选框
const state = reactive({
    selectedRowKeys: [],
});
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
const onSelectChange = (selectedRowKeys, selectedRows) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    console.log('selectedRowKeys changed: ', selectedRows);
    state.selectedRowKeys = selectedRowKeys;
};

// 可编辑
const editableData = reactive({});
const edit = (key) => {
    editableData[key] = cloneDeep(
        dataSource.value.filter((item, index) => {
            return key === index;
        })[0]
    );
};
const save = (key) => {
    Object.assign(dataSource.value.filter((item, index) => key === index)[0], editableData[key]);
    Object.assign(cloneDeepData['value']['details'].filter((item, index) => key === index)[0], editableData[key]);
    delete editableData[key];
    modifyCorrAmt(cloneDeepData.value, { amtUnit: topForm.amt_unit }).then((res:any) => {
        if (res.state == '200') {
            message.success(res.msg || '修改成功！');
        } else {
            message.error(res.msg || '修改失败！');
        }
        mainQuery();
    });
};

// 区划树数据
const apiTreeData = ref([]);

// 查询左侧边栏区划树
const regionTreeData = () => {
    const params = {
        reportDate: selectedDate.year + selectedDate.month + selectedDate.day,
        warnCycle: 1,
    }
    regionTreeQuery(params).then((res: any) => {
        if (res.state == '200') {
            const { hotData, data } = res;
            apiTreeData.value = toTreeData(data) as any;
            // console.log(JSON.stringify(apiTreeData.value));
            message.success(res.msg || '区划树查询成功！');
        } else {
            message.error(res.msg || '区划树查询失败！');
        }
    });
};

// 主查询
let cloneDeepData = ref({}); // 修改确认数的接口传参
const mainQuery = () => {
    Object.keys(editableData).map((key) => {
        delete editableData[key];
    });
    loading.value = true;
    let data = {
        amtUnit: topForm.amt_unit,
        reportDate: selectedDate.year + selectedDate.month + selectedDate.day,
        mofDivCode: regionCode['value'][0],
        warnCycle: 1,
    };
    if(data.mofDivCode == null || data.mofDivCode == undefined) {
        message.warning('未选中区划！')
    }
    if(data.mofDivCode != undefined) {
        reportQuery(data).then((res: any) => {
            loading.value = false;
            if (res.state == '200') {
                const { hotData, data } = res;
                cloneDeepData.value = cloneDeep(data);
                dataSource.value = data.details;
                warning_Level.value = data.wranQuota.warn_level;
                templateQuotas.length ? (templateQuotas.length = 0) : null;
                data.template.quotas.forEach((item, index) => {
                    templateQuotas.push(item);
                });
                getMarkLineData(templateQuotas);
                message.success(res.msg || '报告查询成功！');
            } else {
                cloneDeepData.value = cloneDeep(data);
                dataSource.value = [];
                warning_Level.value = null;
                message.error(res.msg || '报告查询失败！');
            }
        });
    }else {
        loading.value = false;
    }
};

// 重新生成报告
const generateReport = () => {
    let data = {
        amtUnit: topForm.amt_unit,
        reportDate: dayjs(topForm.yearAndmonth).format('YYYY-MM-DD'),
        mofDivCode: regionCode['value'][0],
        warnCycle: 1,
    };
    generateQuery(data).then((res:any) => {
        if (res.state == '200') {
            message.success(res.msg || '报告生成成功！');
            mainQuery();
        } else {
            message.error(res.msg || '报告生成失败！');
        }
    });
}

// echarts相关
// 右上角，switch开关切换表格与图表的参数
let tableOrEcharts = ref(true)
// 期初+收入的项目
const echartsData = reactive({
    'data1':[] as any,
    'data2':[] as any,
    'data3':[] as any,
})
// 监听表格数据，动态生成echarts图标数据
watch(() => dataSource.value, (newValue,oldValue) => {
    echartsData['data1'].length = 0;
    echartsData['data2'].length = 0;
    echartsData['data3'].length = 0;
    if(newValue.length > 0) {
        newValue.forEach((item,index,arr) => {
            if((item['itemGroup'] == '期初数' || item['itemGroup'] == '本期流入') && item['itemName'] != '本期库款流入') {
                echartsData.data1.push({'value':item['corrAmt'],'name':item['itemName']})
                echartsData.data3.push({
                        name: item['itemName'],
                        type: 'bar',
                        stack: 'AD',
                        data: [item['corrAmt'] ? Number(item['corrAmt']) : 0],
                        markLine: warning_Level.value > 0
                            ? {
                                  symbol: 'none', //去掉箭头
                                  tooltip: { formatter: '{b}: {c}' },
                                  label: { show: true, formatter: '{b}: {c}' },
                                  data: markLineData,
                              }
                            : 'none',
                })
            }
            if(item['itemGroup'] == '本期流出' && item['itemName'] != '本期库款流出') {
                echartsData.data2.push({'value':item['corrAmt'],'name':item['itemName']})
                echartsData.data3.push({
                        name: item['itemName'],
                        type: 'bar',
                        stack: 'BD',
                        data: [item['corrAmt'] ? Number(item['corrAmt']) : 0],
                })
            }
        })
    }
    
})

onMounted(() => {
    // 查询左侧边栏区划树
    regionTreeData();
});
</script>

<style lang="less" scoped>
.showOrhide {
    display: none;
}
.ant_layout {
    display: flex;
    justify-content: space-between;
    height: 100%;
    width: 100%;
    .layout_sider {
        display: inline-block;
        padding: 20px;
        height: 100%;
        width: 20%;
        border: 2px solid #f6f6f6;
        overflow: auto;
    }
    .layout_content {
        display: inline-block;
        // flex: 1;
        padding: 20px;
        width: 80%;
        height: 100%;
        border: 2px solid #f6f6f6;
        overflow: auto;

        .content_opertors {
            display: flex;
            justify-content: space-between;
            height: 32px;
            margin-bottom: 20px;

            .left .ant-btn {
                margin-right: 16px;
            }

            .right {
                display: flex;
                .ant-form-item {
                    margin-bottom: 0;
                }
                .ant-switch {
                    background-color: #1890ff;
                }
            }
        }
        .grid {
            margin-top: 20px;
            height: calc(100% - 196px);
        }
        .my_echarts {
            margin-top: 20px;
            // height: calc(100% - 196px);
            background-color: #f1eeeb59;
            overflow: hidden;
        }
        .my_echarts>div {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
        }
        :deep(.ant-table-cell) {
            overflow: hidden;
        }
        :deep(.ant-table-body) {
            height: 100%;
        }
        :deep(.ant-progress-outer) {
            margin-right: 0 !important;
            // padding-right: 0 !important;
            width: 120px;
        }
        :deep(.ant-progress-inner) {
            background-color: #cabfbf;
        }
        :deep(.ant-progress-text) {
            display: block;
            width: auto;
            text-align: center;
        }
    }
}
</style>
